import { Component, HostBinding, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

class Contributor {
  name: string;
  email: string;
  commits: number;
  avatar_url: string;
}

@Component({
  selector: 'fui-contributors',
  templateUrl: './contributors.component.html',
  styleUrls: ['./contributors.component.sass'],
})
export class ContributorsComponent implements OnInit {
  @HostBinding('class.fui-contributors') hostClass = true;

  contributors: Contributor[] = [];

  private get headers(): HttpHeaders {
    return new HttpHeaders({
      'Content-Type': 'application/json;charset=UTF-8',
      'PRIVATE-TOKEN': 'PqB2N52iR4EC9LYznRxz',
    });
  }

  constructor(
    private http: HttpClient,
  ) { }

  ngOnInit(): void {
    this.getContributors();
  }

  getContributors() {
    this.get('http://172.16.1.41:10080/api/v4/projects/1395/repository/contributors', {
      order_by: 'commits',
      sort: 'desc',
    }).subscribe((contributors) => {
      this.contributors = contributors
        .filter((contributor) => contributor.commits > 5);

      this.contributors.forEach((contributor) => {
        this.get('http://172.16.1.41:10080/api/v4/users', {
          search: contributor.email,
        }).subscribe((users) => {
          if (users.length > 0) {
            const user = users[0];
            contributor.avatar_url = user.avatar_url;
          }
        });
      });
    });
  }

  private get(path: string, params: any): Observable<any> {
    return this.http.get(path, { headers: this.headers, params });
  }
}
